<template>
  <div class="flex flex-col p-5 bg-gray-50 min-h-screen">
    <!-- 顶部标题区域 -->
    <div class="flex justify-between items-center mb-8">
      <div class="flex-1">
        <h1 class="text-3xl font-bold text-gray-800">仪表盘</h1>
        <p class="text-gray-500">欢迎回来、张明！这里是你的任务概览</p>
      </div>
      <div class="flex gap-3">
        <button class="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-md hover:bg-gray-50 transition-colors">
          <i class="w-4 h-4 bg-gray-500 rounded"></i>
          筛选
        </button>
        <button class="flex items-center justify-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors" @click="showAddTaskModal = true">
          <span class="h-4 mt-[-2rem] text-8">+</span>
          新建任务
        </button>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="grid grid-cols-4 gap-5 mb-8">
      <div v-for="stat in stats" :key="stat.id" class="flex justify-between items-center p-5 bg-white rounded-lg shadow-sm">
        <div>
          <div class="text-gray-500 text-sm mb-1">{{ stat.label }}</div>
          <div class="text-2xl font-bold text-gray-800 mb-1">{{ stat.value }}</div>
          <div :class="['text-xs', stat.change.includes('↑') ? 'text-green-500' : 'text-red-500']">
            {{ stat.change }}
          </div>
        </div>
        <div class="w-12 h-12 bg-blue-50 rounded-full flex items-center justify-center text-blue-500 text-xl">
          <i class="w-6 h-6"></i>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="flex-1 grid grid-cols-3 gap-5 mb-8">
      <!-- 任务完成趋势图 -->
      <div class="flex flex-col col-span-2 bg-white rounded-lg shadow-sm p-5">
        <div class="flex justify-between items-center mb-5">
          <h3 class="text-lg font-bold text-gray-800">任务完成趋势</h3>
          <div class="flex gap-2">
            <button v-for="period in timePeriods" :key="period" 
              :class="['px-3 py-1 text-xs rounded', trendTimeFilter === period ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200']" 
              @click="trendTimeFilter = period">
              {{ period }}
            </button>
          </div>
        </div>
        <div class="flex-1">
          <MyChart :chart-options="trendChartOptions" />
        </div>
      </div>

      <!-- 任务分类占比饼图 -->
      <div class="flex flex-col bg-white rounded-lg shadow-sm p-5">
        <div class="flex justify-between items-center mb-5">
          <h3 class="text-lg font-bold text-gray-800">任务分类占比</h3>
          <div class="flex gap-2">
            <button v-for="period in timePeriods" :key="period" 
              :class="['px-3 py-1 text-xs rounded', pieTimeFilter === period ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200']" 
              @click="pieTimeFilter = period">
              {{ period }}
            </button>
          </div>
        </div>
        <div class="flex-1">
          <MyChart :chart-options="pieChartOptions" />
        </div>
      </div>
    </div>

    <!-- 任务列表区域 -->
    <div class="grid grid-cols-2 gap-5">
      <!-- 今日任务列表 -->
      <div class="bg-white rounded-lg shadow-sm">
        <div class="p-5 pt-5 pb-0">
          <h3 class="text-lg font-bold text-gray-800">今日任务</h3>
        </div>
        <div class="p-5">
          <div v-for="task in todayTasks" :key="task.id" class="flex items-center py-3 border-b last:border-0 border-gray-50">
            <div class="mr-3 h-16px">
              <input type="checkbox" :id="`task-${task.id}`" v-model="task.completed" class="w-4 h-4 rounded text-blue-500 focus:ring-blue-500 hover:ring-blue-500 cursor-pointer">
            </div>
            <div class="flex-1 flex items-center gap-2">
              <span :class="['text-gray-800', task.completed ? 'line-through text-gray-400' : '']">
                {{ task.title }}
              </span>
              <span class="text-xs text-white px-2 py-0.5 rounded-full" :style="`background: ${getTagColor(task.tag)}`">
                {{ task.tag }}
              </span>
            </div>
            <div class="text-gray-400 text-sm mr-3">{{ task.time }}</div>
            <div class="relative group">
              <button class="w-8 h-8 flex items-center justify-center text-gray-400 hover:text-gray-600 bg-transparent">
                <i class="w-1.5 h-6 flex flex-col justify-between">
                  <span class="w-full h-1 rounded-full bg-current"></span>
                  <span class="w-full h-1 rounded-full bg-current"></span>
                  <span class="w-full h-1 rounded-full bg-current"></span>
                </i>
              </button>
              <div class="absolute right-0 mt-2 w-40 bg-white shadow-lg rounded-md p-2 hidden group-hover:block z-10">
                <button class="w-full text-left px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100 rounded">编辑任务</button>
                <button class="w-full text-left px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100 rounded">标记为重要</button>
                <button class="w-full text-left px-3 py-1.5 text-sm text-red-500 hover:bg-gray-100 rounded">删除任务</button>
              </div>
            </div>
          </div>
          <!-- 查看全部按钮 -->
          <div class="py-3 flex justify-center">
            <button class="text-blue-500 hover:text-blue-600 flex items-center gap-1 text-sm bg-transparent">
              查看全部
              <span>&gt;</span>
            </button>
          </div>
        </div>
      </div>

      <!-- 即将到期列表 -->
      <div class="bg-white rounded-lg shadow-sm">
        <div class="p-5 pt-5 pb-0">
          <h3 class="text-lg font-bold text-gray-800">即将到期</h3>
        </div>
        <div class="p-5">
          <div v-for="task in upcomingTasks" :key="task.id" class="flex items-center py-3 border-b last:border-0 border-gray-50">
            <!-- 圆形图例表示剩余时间 -->
            <div :class="`w-3 h-3 rounded-full mr-3 bg-${getTimeRemainingColor(task.deadline)} flex items-center justify-center text-white text-xs`">
              <i class="w-2 h-2"></i>
            </div>
            <div class="flex-1 flex items-center gap-2">
              <span class="text-gray-800">{{ task.title }}</span>
              <span class="text-xs text-white px-2 py-0.5 rounded-full" :style="`background: ${getTagColor(task.tag)}`">
                {{ task.tag }}
              </span>
            </div>
            <div class="text-gray-400 text-sm mr-3" :class="`text-${getTimeRemainingColor(task.deadline)}`">{{ task.deadline }}</div>
            <div class="relative group">
              <button class="w-8 h-8 flex items-center justify-center text-gray-400 hover:text-gray-600 bg-transparent">
                <i class="w-1.5 h-6 flex flex-col justify-between">
                  <span class="w-full h-1 rounded-full bg-current"></span>
                  <span class="w-full h-1 rounded-full bg-current"></span>
                  <span class="w-full h-1 rounded-full bg-current"></span>
                </i>
              </button>
              <div class="absolute right-0 mt-2 w-40 bg-white shadow-lg rounded-md p-2 hidden group-hover:block z-10">
                <button class="w-full text-left px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100 rounded">完成任务</button>
                <button class="w-full text-left px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100 rounded">延期</button>
                <button class="w-full text-left px-3 py-1.5 text-sm text-red-500 hover:bg-gray-100 rounded">删除任务</button>
              </div>
            </div>
          </div>
          <!-- 查看全部按钮 -->
          <div class="py-3 flex justify-center">
            <button class="text-blue-500 hover:text-blue-600 flex items-center gap-1 text-sm bg-transparent">
              查看全部
              <span>&gt;</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新建任务模态框 -->
    <DraggableModal 
      v-model:visible="showAddTaskModal" 
      title="新建任务" 
      width="600px"
      :initial-position="{ top: '50%', left: '50%' }"
      draggable
      show-close
    >
      <div class="p-2">
        <n-form ref="formRef" :model="newTask" :rules="rules" class="space-y-4">
          <n-form-item label="任务标题" path="title" :label-style="{ color: '#fff' }">
            <n-input 
              v-model:value="newTask.title" 
              placeholder="请输入任务标题"
              :style="{ backgroundColor: 'rgba(255, 255, 255, 0.1)', borderColor: 'rgba(127, 219, 255, 0.3)', color: '#fff' }"
            />
          </n-form-item>
          
          <div class="grid grid-cols-2 gap-4">
            <n-form-item label="任务标签" path="tag" :label-style="{ color: '#fff' }">
              <n-select 
                v-model:value="newTask.tag" 
                placeholder="请选择任务标签"
                :options="tagOptions"
                :style="{ backgroundColor: 'rgba(255, 255, 255, 0.1)', borderColor: 'rgba(127, 219, 255, 0.3)', color: '#fff' }"
                :render-label="renderTagLabel"
              />
            </n-form-item>
            
            <n-form-item label="截止时间" path="deadline" :label-style="{ color: '#fff' }">
              <n-date-picker 
                v-model:value="newTask.deadline"
                type="datetime"
                placeholder="选择截止时间"
                :style="{ backgroundColor: 'rgba(255, 255, 255, 0.1)', borderColor: 'rgba(127, 219, 255, 0.3)', color: '#fff' }"
              />
            </n-form-item>
          </div>
          
          <n-form-item label="任务描述" path="description" :label-style="{ color: '#fff' }">
            <n-input 
              v-model:value="newTask.description" 
              placeholder="请输入任务描述"
              type="textarea"
              :rows="4"
              :style="{ backgroundColor: 'rgba(255, 255, 255, 0.1)', borderColor: 'rgba(127, 219, 255, 0.3)', color: '#fff' }"
            />
          </n-form-item>
        </n-form>
      </div>
      <template #footer>
        <n-button type="default" @click="showAddTaskModal = false" :style="{ color: '#0074d9', borderColor: '#0074d9' }">取消</n-button>
        <n-button type="primary" @click="handleAddTask" :style="{ backgroundColor: '#0074d9', borderColor: '#0074d9' }">创建</n-button>
      </template>
    </DraggableModal>
  </div>
</template>

<script setup lang="jsx">
import { ref, computed } from 'vue'
import MyChart from '@/components/MyChart.vue'
import DraggableModal from '@/components/DraggableModal.vue'
import { NForm, NFormItem, NInput, NSelect, NDatePicker, NButton, useMessage } from 'naive-ui'
import { globalVariable } from '@/stores/index.js'

const message = useMessage()
// 获取全局变量store
const store = globalVariable()

// 控制新建任务模态框的显示/隐藏
const showAddTaskModal = ref(false)

// 表单引用
const formRef = ref(null)

// 新任务表单数据
const newTask = ref({
  title: '',
  tag: '',
  deadline: null,
  description: ''
})

// 标签选项
const tagOptions = computed(() => {
  return store.categories.map(category => ({
    label: category.name,
    value: category.name,
    ...category
  }))
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { max: 50, message: '任务标题不能超过50个字符', trigger: 'blur' }
  ],
  tag: [
    { required: true, message: '请选择任务标签', trigger: 'change' }
  ],
  deadline: [
    {
      required: true, message: '请选择截止时间', trigger: ['change', 'blur'],
      validator: (rule, value) => {
        console.log(value)
        // 检查值是否存在且是有效的日期对象
        return value !== null && value !== undefined
        // && !isNaN(Date.parse(value))
      }
    }
  ]
}

// 渲染标签选项的自定义样式
const renderTagLabel = (option) => {
  console.log(option)
  return (
    <div class="flex items-center">
      <div class={`w-3 h-3 rounded-full mr-2`} style={`background: ${option.color}`}></div>
      <span>{option.label}</span>
    </div>
  )
}

// 统计数据
const stats = ref([
  { id: 1, label: '总任务', value: 28, change: '↑12% 较上月' },
  { id: 2, label: '已完成', value: 18, change: '↑8% 较上月' },
  { id: 3, label: '进行中', value: 7, change: '↑5% 较上月' },
  { id: 4, label: '逾期', value: 3, change: '↓2% 较上月' }
])

// 时间筛选选项
const timePeriods = ['周', '月', '年']
const trendTimeFilter = ref('周')
const pieTimeFilter = ref('周')

// 今日任务数据
const todayTasks = ref([
  { id: 1, title: '完成项目需求文档编写', tag: '工作', time: '14:30', completed: false },
  { id: 2, title: '聚餐', tag: '个人', time: '10:00', completed: true },
  { id: 3, title: '项目代码审查', tag: '学习', time: '16:00', completed: false }
])

// 即将到期任务数据
const upcomingTasks = ref([
  { id: 4, title: 'UI设计稿交付', tag: '工作', deadline: '今天 17:00', priority: 'high' },
  { id: 5, title: '客户需求沟通', tag: '工作', deadline: '明天 09:30', priority: 'medium' },
  { id: 6, title: '整理项目文档', tag: '工作', deadline: '后天 12:00', priority: 'low' }
])

// 标签颜色映射
const getTagColor = (tag) => {
  return store.categories.find(cat => cat.name === tag)?.color || '#9ca3af'
}

// 剩余时间颜色映射（红、黄、灰表示剩余时间由短到长）
const getTimeRemainingColor = (deadline) => {
  // 这里简单实现，根据deadline字符串判断剩余时间
  if (deadline.includes('今天')) {
    return 'red-500' // 今天到期，红色
  } else if (deadline.includes('明天')) {
    return 'yellow-500' // 明天到期，黄色
  } else {
    return 'gray-400' // 其他时间，灰色
  }
}

// 处理添加任务
const handleAddTask = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    // 模拟添加任务逻辑
    console.log('添加新任务:', newTask.value)
    
    // 重置表单
    formRef.value.restoreValidation()
    newTask.value = {
      title: '',
      tag: '',
      deadline: null,
      description: ''
    }

    // 关闭模态框
    showAddTaskModal.value = false
    
    // 显示成功提示（实际项目中可以使用通知组件）
    message.success('任务创建成功！')
  } catch (error) {
    // 表单验证失败
    console.log('表单验证失败:', error)
  }
}

// 趋势图数据 - 根据时间筛选切换
const trendChartData = computed(() => {
  if (trendTimeFilter.value === '周') {
    return {
      categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      completed: [2, 4, 3, 5, 3, 2, 1],
      added: [3, 2, 4, 3, 4, 1, 2]
    }
  } else if (trendTimeFilter.value === '月') {
    return {
      categories: ['1月', '2月', '3月', '4月', '5月', '6月'],
      completed: [45, 59, 80, 81, 56, 55],
      added: [60, 80, 75, 90, 70, 65]
    }
  } else {
    return {
      categories: ['2020', '2021', '2022', '2023', '2024'],
      completed: [320, 332, 301, 334, 390],
      added: [350, 370, 360, 400, 450]
    }
  }
})

// 饼图数据 - 根据时间筛选切换
const pieChartData = computed(() => {
  const colorMap = {
    '工作': '#3b82f6',
    '会议': '#10b981',
    '代码': '#f59e0b',
    '设计': '#ef4444',
    '客户': '#6b7280',
    '文档': '#a855f7'
  }
  
  if (pieTimeFilter.value === '周') {
    return [
      { value: 8, name: '工作', itemStyle: { color: colorMap['工作'] } },
      { value: 3, name: '会议', itemStyle: { color: colorMap['会议'] } },
      { value: 4, name: '代码', itemStyle: { color: colorMap['代码'] } },
      { value: 3, name: '设计', itemStyle: { color: colorMap['设计'] } },
      { value: 2, name: '客户', itemStyle: { color: colorMap['客户'] } },
      { value: 4, name: '文档', itemStyle: { color: colorMap['文档'] } }
    ]
  } else if (pieTimeFilter.value === '月') {
    return [
      { value: 30, name: '工作', itemStyle: { color: colorMap['工作'] } },
      { value: 12, name: '会议', itemStyle: { color: colorMap['会议'] } },
      { value: 15, name: '代码', itemStyle: { color: colorMap['代码'] } },
      { value: 10, name: '设计', itemStyle: { color: colorMap['设计'] } },
      { value: 8, name: '客户', itemStyle: { color: colorMap['客户'] } },
      { value: 15, name: '文档', itemStyle: { color: colorMap['文档'] } }
    ]
  } else {
    return [
      { value: 150, name: '工作', itemStyle: { color: colorMap['工作'] } },
      { value: 80, name: '会议', itemStyle: { color: colorMap['会议'] } },
      { value: 90, name: '代码', itemStyle: { color: colorMap['代码'] } },
      { value: 70, name: '设计', itemStyle: { color: colorMap['设计'] } },
      { value: 60, name: '客户', itemStyle: { color: colorMap['客户'] } },
      { value: 80, name: '文档', itemStyle: { color: colorMap['文档'] } }
    ]
  }
})

// 趋势图配置
const trendChartOptions = computed(() => {
  return {
    grid: {
      top: 20,
      bottom: 20,
      left: 20,
      right: 20
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: {
      data: ['已完成', '新增任务'],
      top: 0
    },
    xAxis: {
      type: 'category',
      data: trendChartData.value.categories
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '已完成',
        type: 'bar',
        barWidth: 40,
        itemStyle: {
          borderRadius: 4
        },
        data: trendChartData.value.completed,
        color: '#3b82f6'
      },
      {
        name: '新增任务',
        type: 'line',
        data: trendChartData.value.added,
        color: '#ef4444'
      }
    ]
  }
})

// 饼图配置
const pieChartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: { fontSize: 12 }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data: pieChartData.value
      }
    ]
  }
})
</script>

<style scoped>
/* 保留少量必要的自定义样式 */
[data-icon]:before {
  content: attr(data-icon);
}

/* 图标样式 */
.icon-filter {
  background-image: url('');
}

.icon-plus {
  background-image: url('');
}

.icon-ellipsis-v {
  background-image: url('');
}
</style>